package cn.sfa.common.taglib;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.entity.users.SaleUsersLogin;

/**
 * 
 * 类名称：HeaderTag 类描述：jsp页面的头部信息自定义标签类 创建人：lenovo 创建时间：2012-2-9 上午10:23:00 修改备注：
 * 
 * @version v1.0
 */
public class MainHeaderTagbak extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1355396206595036725L;

	Logger logger = LoggerFactory.getLogger(MainHeaderTagbak.class);

	String menuId;

	@Override
	public int doEndTag() throws JspException {

		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {

		String path = (String) pageContext.getRequest().getAttribute("path");

		String curURL = (String) pageContext.getRequest().getAttribute(
				"curPath");

		SaleUsersLogin user = (SaleUsersLogin) pageContext.getSession()
				.getAttribute("user");

		String userType = null;
		try {
			userType = user.getUserType();
			if ("USERTYPE_1".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_2".equals(userType)) {
				userType = "o1";
			} else if ("USERTYPE_4".equals(userType)) {
				userType = "i1";
			} else if ("USERTYPE_3".equals(userType)) {
				userType = "i1";
			}
		} catch (Exception e) {

			HttpServletResponse response = (HttpServletResponse) pageContext
					.getResponse();
			HttpServletRequest request = (HttpServletRequest) pageContext
					.getRequest();
			try {
				response.sendRedirect(request.getContextPath()
						+ "/sfa/sfa/index.jsp");// 重定向登录页面
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		String navURL = "";
		String menuURL = "";
		// navURL = "/"+curURL.split("/sfa/")[1];//导航菜单链接
		// navURL ="/"+navURL.split("/")[1]+"/index";
		navURL = "/" + curURL.split("/")[1] + "/index";
		menuURL = curURL.substring(1, curURL.length());
		// String menuURL= curURL.split("/sfa/")[1];//左菜单链接
		logger.info("menuURL:" + menuURL + "  | navURL:" + navURL);
		if ("login".equals(curURL.split("/")[2])) {// 登录的时候进行菜单初始化
			navURL = "/news/index";
		}

		StringBuffer buffer = new StringBuffer();

		String dir = HeaderTag.class.getResource("/").getPath();
		dir = dir.replace("%20", " ");// 对空格进行转义(否则无法识别路径)

		String cpath = dir + "menuxml//MenuConfig.xml";
		File f = new File(cpath);

		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(f);

			// 获取根元素
			Element root = document.getRootElement();

			// 获取导航菜单
			Element navMenu = (Element) root
					.selectSingleNode("//Navigation[@Url='" + navURL + "']");

			// TODO:获取所有的导航菜单
			List navList = root.selectNodes("Navigation");

			buffer.append("    <div class=\"top-header\">");
			buffer.append("        <div class=\"userinfo\">");
			buffer.append("            <img src='"
					+ path
					+ "/statics/images/icon-user.gif' style=\"margin-bottom: -6px; margin-right: 4px;\" /><span");
			buffer.append("                id=\"username\">"
					+ user.getUserName()
					+ "("
					+ user.getLoginName()
					+ ")</span>，您好！<a href=\"" + path
					+ "/login/index/logout\">注销</a>");
			buffer.append("        </div>");
			buffer.append("    </div>");
			buffer.append("    <div class=\"container\">");
			buffer.append("        <!----------- 页面头部 ------------------>");
			buffer.append("        <div class=\"header\">");
			buffer.append("           <h1>");
			buffer.append("               <span>CRM客户关系管理系统</span>");
			buffer.append("            </h1>");
			buffer.append("            <!-----------  网站导航 ------------------>");
			buffer.append("           <ul class=\"navigation\" id=\"navigation\">");

			String navLevel = "";
			int index = 0;
			int endIndex = navList.size();

			for (Iterator<Element> iter = navList.iterator(); iter.hasNext();) {
				Element navElement = iter.next();

				navLevel = navElement.attributeValue("level");

				if (Arrays.asList(navLevel.split(",")).contains(userType)) {

					if (index == 0) {
						buffer.append("<li class=\"navli-l\">");
					} else if (index == endIndex) {
						buffer.append("<li class=\"bgnone navli-r\">");
					} else {
						buffer.append("<li class=\"navli-m\">");
					}

					if (navMenu.attributeValue("Id").equals(
							navElement.attributeValue("Id"))) {
						// buffer.append("<li class='nownav'><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
						buffer.append("<a href=\"" + path
								+ navElement.attributeValue("Url")
								+ "\" class=\"current\"><span>"
								+ navElement.attributeValue("Name")
								+ "</span></a>");
					} else {
						// buffer.append("<li><a href='"+path+navElement.attributeValue("Url")+"'><span>"+navElement.attributeValue("Name")+"</span></a>");
						buffer.append("<a href=\"" + path
								+ navElement.attributeValue("Url")
								+ "\" ><span>"
								+ navElement.attributeValue("Name")
								+ "</span></a>");
					}
					buffer.append("</li>");

				}
				index++;
			}
			buffer.append("            </ul>");
			buffer.append("            <div style=\"clear: both\">");
			buffer.append("            </div>");
			buffer.append("        </div>");

			buffer.append("   <!----------- 页面内容 ------------------>");
			buffer.append("    <div class=\"content\" id=\"content\">");

			// 获取当前菜单
			// 当前菜单存在三种情况:1.当前菜单为主菜单链接;2.当前菜单为左菜单链接;3.当前菜单不在MenuConfig.xml文件中
			Element currentMenu = (Element) root
					.selectSingleNode("//Columns/Column[@Url='" + menuURL
							+ "']");

			if (CommonUtil.isEmpty(currentMenu)) {
				// currentMenu=navMenu.element("Group").element("Columns").element("Column");

			} else if (navURL.equals("/" + menuURL)) {
				// currentMenu=navMenu.element("Group").element("Columns").element("Column");//TODO:如果为空,设置为第一个菜单项
			}
			// TODO:如果当前是navMenu没有子元素,则不显示左边菜单
			if (CommonUtil.isEmpty(navMenu.element("Group"))) {

				buffer.append("<div class='navsite'>"
						+ "<p> 您的位置：首页&nbsp;&gt;&gt;&nbsp;"
						+ navMenu.attributeValue("Name"));
				buffer.append("</p>" + "</div>");
			} else {
				buffer.append("<div class='navsite'><p>您的位置：<a href=''>"
						+ navMenu.attributeValue("Name") + "</a>");
				if (!CommonUtil.isEmpty(currentMenu)) {
					buffer.append("&nbsp;&gt;&gt;&nbsp;"
							+ "<a href=''>"
							+ currentMenu.getParent().getParent()
									.element("Name").getText() + "</a>");
					buffer.append("&nbsp;&gt;&gt;&nbsp;"
							+ currentMenu.attributeValue("Name"));
				}
				buffer.append("</p></div>");

				List leftMenu = navMenu.selectNodes("Group");
				buffer.append(" <div class=\"webpart3 submenu\">");
				buffer.append(" 	<div class=\"webpart-head\">");
				buffer.append("   		 <div class=\"webpart-head-item\">");
				buffer.append("    			  <img src='"
						+ path
						+ "/statics/images/add.gif' style=\"margin-right: 4px;\" />");
				// if(!CommonUtil.isEmpty(currentMenu)){
				buffer.append(navMenu.attributeValue("Name"));
				// }
				buffer.append("   		 </div>");
				buffer.append(" 	</div>");
				buffer.append(" 	<div class=\"webpart-main\">");
				buffer.append(" 		<div class=\"webpart-main-item submenuitem\" style=\"padding-top: 8px;\">");
				// TODO:左边菜单开始
				for (Iterator<Element> iter = leftMenu.iterator(); iter
						.hasNext();) {
					Element menu = iter.next();
					Element cols = menu.element("Columns");
					if (!CommonUtil.isEmpty(cols)) {
						String menuLevel = "1";// 初始化为最低级别
						buffer.append("<h1>" + menu.elementText("Name")
								+ "</h1><ul>");
						List colList = cols.selectNodes("Column");
						for (Iterator<Element> iter2 = colList.iterator(); iter2
								.hasNext();) {
							Element col = iter2.next();
							menuLevel = col.attributeValue("level");
							/* class="click" */
							if (!CommonUtil.isEmpty(currentMenu)
									&& currentMenu.attributeValue("id").equals(
											col.attributeValue("id"))) {
								if (Arrays.asList(menuLevel.split(","))
										.contains(userType)) {
									buffer.append("<li class=' current'><a href='"
											+ path
											+ "/"
											+ col.attributeValue("Url")
											+ "'>"
											+ col.attributeValue("Name")
											+ "</a></li>");
								} else {
									buffer.append("<li class=' current'><a style='color:gray' href='javascript:art.dialog( {"
											+ "id : \"loading\","
											+ "lock : true,"
											+ "drag : false,"
											+ "icon: \"error\","
											+ "resize : false,"
											+ "content : \"对不起,您没有权限进行此操作!\""
											+ "});'>"
											+ col.attributeValue("Name")
											+ "</a></li>");
								}
							} else {
								if (Arrays.asList(menuLevel.split(","))
										.contains(userType)) {
									buffer.append("<li ><a href='" + path + "/"
											+ col.attributeValue("Url") + "'>"
											+ col.attributeValue("Name")
											+ "</a></li>");
								} else {
									buffer.append("<li class='click'><a style='color:gray' href='javascript:art.dialog( {"
											+ "id : \"loading\","
											+ "lock : true,"
											+ "drag : false,"
											+ "icon: \"error\","
											+ "resize : false,"
											+ "content : \"对不起,您没有权限进行此操作!\""
											+ "});'>"
											+ col.attributeValue("Name")
											+ "</a></li>");
								}
							}
						}
					}
					buffer.append("</ul>");
				}
				// TODO:左边菜单结束
				buffer.append("			</div>");
				buffer.append("		</div>");
				buffer.append("		<div class=\"webpart-foot\">");
				buffer.append("			<div class=\"webpart-foot-item\">");
				buffer.append("			</div>");
				buffer.append("		</div>");
				buffer.append("</div>");

				Log.info(buffer.toString());
			}

			JspWriter out = pageContext.getOut();
			try {
				out.println(buffer);// 输出到jsp页面
			} catch (IOException e) {

				e.printStackTrace();
			}

		} catch (DocumentException e1) {

			e1.printStackTrace();
		}

		return super.doStartTag();
	}

}
